from PIL import Image, ImageGrab


class DraggableText:
    def __init__(self, canvas, text, x, y, image):
        self.canvas = canvas
        self.text = text
        self.image = image
        self.x = x
        self.y = y
        self.drag_data = {"x": 0, "y": 0}
        self.create_text()

    def create_text(self):
        self.text_widget = self.canvas.create_text(self.x, self.y, text=self.text, font=("Arial", 12), tags="draggable")

        self.canvas.tag_bind(self.text_widget, "<ButtonPress-1>", self.on_press)
        self.canvas.tag_bind(self.text_widget, "<B1-Motion>", self.on_drag)
        self.canvas.tag_bind(self.text_widget, "<ButtonRelease-1>", self.on_release)

    def on_press(self, event):
        self.drag_data["x"] = event.x
        self.drag_data["y"] = event.y

    def on_drag(self, event):
        dx = event.x - self.drag_data["x"]
        dy = event.y - self.drag_data["y"]
        self.canvas.move(self.text_widget, dx, dy)
        self.drag_data["x"] = event.x
        self.drag_data["y"] = event.y

    def on_release(self, event=None, image=None):
        save_path = "./image/canvas_snapshot.png"
        if self.image is None:
            print("NONE")
        self.image.save(save_path)
        self.image = Image.open(save_path)
        print("text")
        bbox = self.canvas.bbox("image")
        width = bbox[2] - bbox[0]
        height = bbox[3] - bbox[1]
        x = self.canvas.winfo_rootx() + self.canvas.winfo_x() + 2
        print(self.canvas.winfo_rootx())
        print(self.canvas.winfo_x())
        print(x)
        y = self.canvas.winfo_rooty() + self.canvas.winfo_y() + 2
        print(self.canvas.winfo_rooty())
        print(self.canvas.winfo_x())
        print(y)
        print(x,width,height)
        x1 = x + width - 4
        print(self.canvas.winfo_width())
        y1 = y + height - 2
        print(self.canvas.winfo_height())
        image = ImageGrab.grab((self.canvas.winfo_rootx(), self.canvas.winfo_rooty(), self.canvas.winfo_rootx()+width, self.canvas.winfo_rooty()+height))
        image.save(save_path)

        # 保存画布内容为图像文件
        save_path = "../image/canvas_snapshot.png"
        print("保存成功:", save_path)
        if self.image is None:
            print("this image is null")
        pass

    def destroy(self):
        print("destroy")
        self.canvas.tag_unbind(self.text_widget, "<ButtonPress-1>")
        self.canvas.tag_unbind(self.text_widget, "<B1-Motion>")
        self.canvas.tag_unbind(self.text_widget, "<ButtonRelease-1>")
